﻿using Game;
using Engine;
using GameEntitySystem;


namespace SCIENEW
{
	public class CrusherBehavior : DeviceBehavior
	{
        public SubsystemPickables m_subsystemPickables;
        public SubsystemProjectiles m_subsystemProjectiles;
        public SubsystemEnginePower m_subsystemEnginePower;
        public SubsystemTerrain m_SubsystemTerrain;
        public float m_speed = 20;
        public CrusherBehavior(Project project) : base(project) {
            m_subsystemPickables = project.FindSubsystem<SubsystemPickables>(true);
            m_subsystemProjectiles = project.FindSubsystem<SubsystemProjectiles>(true);
            m_subsystemEnginePower = project.FindSubsystem<SubsystemEnginePower>(true);
            m_SubsystemTerrain = project.FindSubsystem<SubsystemTerrain>(true);
        }


		public override void OnHitByProjectile(CellFace cellFace, WorldItem worldItem)
		{
			if (worldItem.ToRemove)
				return;
			if (!m_subsystemEnginePower.IsPowered(cellFace.Point, out IEngineComponent engine) || worldItem.Velocity.Length() < 20f)
				return;
			int l;
			Vector3 v = CellFace.FaceToVector3(cellFace.Face);
			var pickable = worldItem as Pickable;
			int num = pickable?.Count ?? 1;
			if (num > 1)
				return;
			var position = new Vector3(cellFace.Point) + new Vector3(0.5f) - 0.75f * v;
			if (Terrain.ExtractContents(worldItem.Value) == GravelBlock.Index)
			{
				for (l = 0; l < 5; l++)
					if (m_subsystemProjectiles.FireProjectile(StoneChunkBlock.Index, position, -m_speed * v, Vector3.Zero, null) == null)
					{
						m_subsystemPickables.AddPickable(StoneChunkBlock.Index, 1, position, 1f * v, null);
					}
				worldItem.ToRemove = true;
			}
			else
			{
				var list = new List<BlockDropValue>(8);
				BlocksManager.Blocks[Terrain.ExtractContents(worldItem.Value)].GetDropValues(m_SubsystemTerrain, worldItem.Value, 0, 3, list, out bool s);
				if (list.Count == 0)
					return;
				for (l = 0; l < list.Count; l++)
				{
					var blockDropValue = list[l];
					int a = 0;
					if (list.Count > 1)
					{
						a = 1;
					}
					for (int i = 0; i < blockDropValue.Count + a; i++)
						if (m_subsystemProjectiles.FireProjectile(blockDropValue.Value, position, -m_speed * v, Vector3.Zero, null) == null)
						{
							m_subsystemPickables.AddPickable(blockDropValue.Value, 1, position, 1f * v, null);
						}
				}
				worldItem.ToRemove = true;
			}
		}
	}
}
